package com.huadao.pda.login;

import android.content.Intent;
import android.text.TextUtils;
import android.widget.EditText;

import com.huadao.pda.R;
import com.huadao.pda.base.BaseActivity;
import com.huadao.pda.data.bean.DeviceInfo;
import com.huadao.pda.data.bean.User;
import com.huadao.pda.data.http.RetrofitHelper;
import com.huadao.pda.main.MainActivity;
import com.huadao.pda.main.PdaApplication;
import com.huadao.pda.main.scanView.ScanDF;

import butterknife.BindView;
import butterknife.OnClick;

public class LoginActivity extends BaseActivity implements ILoginContract.ILoginView {
    @BindView(R.id.et_username)
    EditText etUsername;
    @BindView(R.id.et_password)
    EditText etPassword;

    private LoginPresenter presenter;

    @Override
    protected void init() {
        presenter = new LoginPresenter(this);
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_login;
    }

    @OnClick(R.id.btn_login)
    public void onLoginClicked() {
        if (!presenter.isDeviceCreated()) {
            presenter.createDevice("正在登陆");
        } else {
            login();
        }
    }

    private void login() {
        String err = checkData();
        if (err != null) {
            showDialogMessage("", err);
        } else {
            presenter.login(etUsername.getText().toString(), etPassword.getText().toString());
        }
    }

    private String checkData() {
        String err = null;
        if (TextUtils.isEmpty(etUsername.getText())) {
            err = "用户名不能为空";
        } else if (TextUtils.isEmpty(etPassword.getText())) {
            err = "密码不能为空";
        }
        return err;
    }

    @Override
    public void createDeviceResult(DeviceInfo deviceInfo) {
        PdaApplication.getInstance().setDeviceInfo(deviceInfo);
//        showToast("创建设备成功");
        login();
    }

    @Override
    public void onLoginResult(String token) {
        PdaApplication.getInstance().setToken(token);
        RetrofitHelper.getInstance(this).reInit();
        PdaApplication.getInstance().setUserName(etUsername.getText().toString());
        presenter=new LoginPresenter(this);
//        showToast("登陆成功");
        presenter.bindPDA();

        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    protected void onDestroy() {
        presenter.detachView();
        super.onDestroy();
    }
}
